<template>
  <view class="test-container">
    <view class="header">
      <text class="title">在线状态测试</text>
    </view>
    
    <view class="status-section">
      <text class="section-title">当前用户状态</text>
      <view class="status-item">
        <text>用户ID: {{ currentUserId }}</text>
      </view>
      <view class="status-item">
        <text>在线状态: {{ isOnline ? '🟢 在线' : '⚪ 离线' }}</text>
      </view>
    </view>
    
    <view class="friends-section">
      <text class="section-title">好友在线状态</text>
      <view v-for="friend in friends" :key="friend.friend_user_id" class="friend-item">
        <view class="friend-info">
          <text class="friend-name">{{ friend.friend_user_name }}</text>
          <text class="friend-status" :class="{ 'online': getFriendOnlineStatus(friend.friend_user_id) }">
            {{ getFriendOnlineStatus(friend.friend_user_id) ? '🟢 在线' : '⚪ 离线' }}
          </text>
        </view>
      </view>
    </view>
    
    <view class="actions">
      <button @click="connectWebSocket" class="action-btn">连接WebSocket</button>
      <button @click="disconnectWebSocket" class="action-btn">断开WebSocket</button>
      <button @click="refreshFriends" class="action-btn">刷新好友列表</button>
    </view>
    
    <view class="logs">
      <text class="section-title">日志</text>
      <view v-for="(log, index) in logs" :key="index" class="log-item">
        <text class="log-time">{{ log.time }}</text>
        <text class="log-message">{{ log.message }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { friendsApi } from '@/api'
import { checkLoginStatus, getCurrentUserId } from '@/utils/auth'

// 状态数据
const currentUserId = ref('')
const isOnline = ref(false)
const friends = ref([])
const logs = ref([])
const friendsOnlineStatus = ref({})

// 添加日志
const addLog = (message) => {
  const time = new Date().toLocaleTimeString()
  logs.value.unshift({ time, message })
  if (logs.value.length > 20) {
    logs.value = logs.value.slice(0, 20)
  }
}

// 获取好友在线状态
const getFriendOnlineStatus = (friendId) => {
  return friendsOnlineStatus.value[friendId] || false
}

// 更新好友在线状态
const updateFriendOnlineStatus = (userId, isOnline) => {
  friendsOnlineStatus.value[userId] = isOnline
  addLog(`好友 ${userId} 状态变更: ${isOnline ? '上线' : '下线'}`)
}

// 更新好友状态列表
const updateFriendsOnlineStatus = (statusList) => {
  statusList.forEach(status => {
    friendsOnlineStatus.value[status.user_id] = status.is_online
  })
  addLog(`收到好友状态列表: ${statusList.length} 个好友`)
}

// 连接WebSocket
const connectWebSocket = () => {
  addLog('尝试连接WebSocket...')
  // 这里可以调用WebSocket连接逻辑
}

// 断开WebSocket
const disconnectWebSocket = () => {
  addLog('断开WebSocket连接')
  // 这里可以调用WebSocket断开逻辑
}

// 刷新好友列表
const refreshFriends = async () => {
  try {
    addLog('刷新好友列表...')
    const res = await friendsApi.getFriendList()
    friends.value = res.data || []
    addLog(`获取到 ${friends.value.length} 个好友`)
  } catch (error) {
    addLog(`刷新好友列表失败: ${error.message}`)
  }
}

// 获取好友列表
const getFriendList = async () => {
  try {
    const res = await friendsApi.getFriendList()
    friends.value = res.data || []
    addLog(`初始获取到 ${friends.value.length} 个好友`)
  } catch (error) {
    addLog(`获取好友列表失败: ${error.message}`)
  }
}

// 组件挂载时
onMounted(() => {
  if (!checkLoginStatus()) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  currentUserId.value = getCurrentUserId(true)
  addLog(`当前用户ID: ${currentUserId.value}`)
  
  getFriendList()
  
  // 监听WebSocket消息
  uni.$on('userStatusChange', (data) => {
    updateFriendOnlineStatus(data.userId, data.isOnline)
  })
  
  uni.$on('friendsStatusUpdate', (statusList) => {
    updateFriendsOnlineStatus(statusList)
  })
  
  addLog('页面已加载，开始监听WebSocket消息')
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  uni.$off('userStatusChange')
  uni.$off('friendsStatusUpdate')
  addLog('页面卸载，清理事件监听')
})
</script>

<style scoped>
.test-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  display: block;
}

.status-section, .friends-section, .actions, .logs {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.status-item {
  margin-bottom: 8px;
}

.friend-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.friend-item:last-child {
  border-bottom: none;
}

.friend-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.friend-name {
  font-weight: bold;
  color: #333;
}

.friend-status {
  color: #666;
}

.friend-status.online {
  color: #4CAF50;
}

.actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  flex: 1;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px;
  font-size: 14px;
}

.log-item {
  border-bottom: 1px solid #eee;
  padding: 8px 0;
}

.log-time {
  color: #999;
  font-size: 12px;
  margin-right: 10px;
}

.log-message {
  color: #333;
  font-size: 14px;
}
</style> 